package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.Gjjutil.Base64Utils;
import com.block.datapush.service.apipush.utils.Gjjutil.RSAUtils;
import com.block.datapush.service.apipush.utils.WuYiGongJiJinUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantThirdBaseInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 *  51公积金双授权
 */
@Service
public class WuYiGongJiJinApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    MerchantThirdBaseInfoMapper merchantThirdBaseInfoMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = StrUtil.format(pushApiKeyParam.getCheckUrl(), pushApiKeyParam.getApiCode());

        // 业务参数json字符串组装
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()).toLowerCase());
        dataMap.put("phone_md5", memberSourceInfo.getMobileMd5().toLowerCase());
//        dataMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()).toLowerCase());
        dataMap.put("gender", WuYiGongJiJinUtil.getSex(memberSourceInfo.getSex()));
        dataMap.put("age",memberSourceInfo.getAge());
        StringBuilder stringBuilder = new StringBuilder(memberSourceInfo.getProvince());
        String workingCity = stringBuilder.append("/").append(memberSourceInfo.getCity()).toString();
        dataMap.put("working_city",workingCity);
        dataMap.put("gjj", WuYiGongJiJinUtil.getGjj(memberSourceInfo.getGjj()));
        dataMap.put("shebao", WuYiGongJiJinUtil.getSheBao(memberSourceInfo.getShebao()));
        dataMap.put("house", WuYiGongJiJinUtil.getHouse(memberSourceInfo.getHouse()));
        dataMap.put("vehicle", WuYiGongJiJinUtil.getCar(memberSourceInfo.getCar()));
        dataMap.put("zhima_score", WuYiGongJiJinUtil.getZhimaScore(memberSourceInfo.getZhima()));
        dataMap.put("insurance", WuYiGongJiJinUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        dataMap.put("occupation", WuYiGongJiJinUtil.getGongzuo(memberSourceInfo.getGongzuo()));
        dataMap.put("business_license",99);
        dataMap.put("education", WuYiGongJiJinUtil.getXueli(memberSourceInfo.getXueli()));
        dataMap.put("credit", WuYiGongJiJinUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        dataMap.put("credit_record", WuYiGongJiJinUtil.getYuqi(memberSourceInfo.getYuqi()));
//        dataMap.put("loan_situation", 99);
        dataMap.put("monthly_salary", WuYiGongJiJinUtil.getShouru(memberSourceInfo.getShouru()));
        dataMap.put("loan_amount", WuYiGongJiJinUtil.getloan(memberSourceInfo.getLoanAmount()));
        dataMap.put("loan_period", WuYiGongJiJinUtil.getloantime(memberSourceInfo.getLoanTime()));
        dataMap.put("loan_purpose", WuYiGongJiJinUtil.getYongtu(memberSourceInfo.getYongtu()));
        dataMap.put("ip", WuYiGongJiJinUtil.getReqip(memberSourceInfo.getReqIp()));
        String jsonString = JSON.toJSONString(dataMap);

        PublicKey publicKey = RSAUtils.loadPublicKey(pushApiKeyParam.getPubKey());
        byte[] encryptByte = RSAUtils.encryptData(jsonString.getBytes("utf-8"), publicKey);
        String content = Base64Utils.encode(encryptByte);

        // 从字符串中得到私钥
        PrivateKey privateKey = RSAUtils.loadPrivateKey(pushApiKeyParam.getPriKey());
        // 加签
        String signStr = RSAUtils.rsaSign(encryptByte, privateKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("sign",signStr);

        log.info("【51公积金双授权】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(dataMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【51公积金双授权】撞库结束【result】{}", result);

        String content1 = resultObject.getString("content");

        byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(content1), privateKey);
        String decryptStr = new String(decryptByte);

        log.info("【51公积金双授权】撞库结束【resultDes】{}", decryptStr);

        JSONObject resultObject1 = JSON.parseObject(decryptStr);
        String code = resultObject1.getString("code");
        String msg = resultObject1.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(dataMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            JSONObject product = resultObject1.getJSONObject("product");
            String serialNo = resultObject1.getString("serial_no");
            String logo = product.getString("logo");
            String name = product.getString("name");
            String institutionName = product.getString("institution_name");
            // 撞库成功之后，商户的机构数据存储

            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo",serialNo);
            infoObject.put("productId",serialNo);
            infoObject.put("productName",name);
            infoObject.put("companyName",institutionName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
//            jsonArray.add(new JSONObject());
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(serialNo);
                extJson.put("serialNo", serialNo);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String serialNo = extJson.getString("serialNo");

        String requestUrl = StrUtil.format(pushApiKeyParam.getRegisterUrl(), pushApiKeyParam.getApiCode());

        Map<Object, Object> bizMap = new HashMap<>();
        bizMap.put("serial_no", serialNo);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
//        bizMap.put("idno", memberSourceInfo.getIdcard());
        bizMap.put("is_authorize", 1);
        String nowDateStr = LocalDateUtil.getNowDateStrByTotalDataTime();
        bizMap.put("authorize_time", nowDateStr);

//        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
//        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        String orderId = extJson.getString("orderId");
        String orderItemId = extJson.getString("orderItemId");
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        bizMap.put("agreement_url", protocolUrl);

        String jsonString = JSON.toJSONString(bizMap);

        PublicKey publicKey = RSAUtils.loadPublicKey(pushApiKeyParam.getPubKey());
        byte[] encryptByte = RSAUtils.encryptData(jsonString.getBytes("utf-8"), publicKey);
        String content = Base64Utils.encode(encryptByte);

        // 从字符串中得到私钥
        PrivateKey privateKey = RSAUtils.loadPrivateKey(pushApiKeyParam.getPriKey());
        // 加签
        String signStr = RSAUtils.rsaSign(encryptByte, privateKey);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",content);
        paramMap.put("sign",signStr);

        log.info("【51公积金双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);
        String content1 = resultObject.getString("content");

        byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(content1), privateKey);
        String decryptStr = new String(decryptByte);

        log.info("【51公积金双授权】导单结束【result】{}", decryptStr);

        JSONObject resultObject1 = JSON.parseObject(decryptStr);
        String code = resultObject1.getString("code");
        String msg = resultObject1.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(code);
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(String.valueOf(code), "0000")){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals(String.valueOf(code), "0000")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encrypt(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key 为空 null");
            return null;
        }// 判断 Key 是否为 16 位
        if (sKey.length() != 16) {
            if(sKey.length()!=32){
                System.out.print("Key 不合法");
                return null;
            }
        }
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); // 此处使用 BASE64 做转码功能，同时能起到 2 次加密的作用。
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
